package com.yami.shop.webservice.api.controller;

import com.yami.shop.bean.enums.FundType;
import com.yami.shop.bean.model.SubscribeFundsRecord;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.webservice.common.service.FundsRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * 资金记录Controller
 * 
 * @author zhangchaoqun
 * @date 2021-10-13
 */
@RestController("apiFundsRecordController")
@RequestMapping("/app/fundsrecord")
@Tag(name = "admin-资金账本")
public class FundsRecordController
{
    @Autowired
    private FundsRecordService fundsRecordService;

    /**
     * 查询资金记录列表
     */
    @GetMapping("/p/list")
    @Operation(summary =  "资金列表", description = "获取资金列表")
    public ServerResponseEntity<PageVO<SubscribeFundsRecord>> list(PageDTO pageDTO, SubscribeFundsRecord fundsRecord)
    {
        fundsRecord.setUserId(SecurityUtils.getUser().getUserId());
        PageVO<SubscribeFundsRecord> page = fundsRecordService.page(pageDTO, fundsRecord);
        List<SubscribeFundsRecord> list = page.getList();
        if(list !=  null && list.size() !=0){
            List<FundType> allToList = FundType.getAllToList();

            for(SubscribeFundsRecord funds:list){
                for(FundType fundType:allToList) {
                    if (funds.getType().equals(fundType.getCode())) {
                        funds.setTypeName(fundType.getInfo());
                    }
                }
            }
            page.setList(list);
        }
        return ServerResponseEntity.success(page);
    }

//    /**
//     * 支付购买商品
//     */
//    @PostMapping("/bugGood")
//    @Operation(summary =  "资金列表", description = "支付购买商品")
//    @Log(title = "账户资金交易", businessType = BusinessType.PAY)
//    @Transactional
//    ServerResponseEntity.success()<PageVO<FundsRecord>> bugGood(@RequestBody FundsRecordVo fundsRecord)
//    {
//        if(StringUtils.isEmpty(fundsRecord.getPwd()) ){
//            return ResponseEntity.showFailMsg("验证码不能为空");
//        }
//        if(StringUtils.isEmpty(fundsRecord.getUserId())){
//            return ResponseEntity.showFailMsg("用户id不能为空");
//        }
//        if( fundsRecord.getTenantId()==null){
//            return ResponseEntity.showFailMsg("参数tenantId不能为空");
//        }
//        if( fundsRecord.getOrderId()==null ){
//            return ResponseEntity.showFailMsg("订单id不能为空");
//        }
//        if(fundsRecord.getbCode()==null ){
//            return ResponseEntity.showFailMsg("店铺编码不能为空");
//        }
//        //验证密码
//        Boolean aBoolean = wapiUserService.checkPayPosswordByUserIdAndPwd(fundsRecord.getUserId(), fundsRecord.getPwd());
//        if(!aBoolean){
//            return ResponseEntity.showFailMsg("密码错误");
//        }
//        String account = wapiUserService.getAccountByUserIdAndMall(fundsRecord.getUserId());
//        //本地账单存储
//        List<FundsRecord> fundsRecordList = new ArrayList<>();
//        //1支付
//        List<FundVo> listFun = new ArrayList<>();
//        String busiName = "商品购买";
//        String outBizNo = fundsRecord.getOrderId().toString()+DateUtils.dateTimeNow("HHmmss");
//        //货款原子
//        FundVo f2 = new FundVo();
//        f2.setExecuteNo("1");
//        f2.setSettlementAccount(account);
//        f2.setSubTransCode(PayCode.PayPaymentSubTrans.getCode());
//        f2.setTransCode(PayCode.PayPaymentTrans.getCode());
//        BigDecimal bai = new BigDecimal(100);
//        BigDecimal dec = fundsRecord.getMoney().multiply(bai);
//        f2.setExchangeAmount(dec.intValue()+"");
//        listFun.add(f2);
//
//        //本地账单存储
//        FundsRecord fundsRecord1 = new FundsRecord();
//        fundsRecord1.setMoney(fundsRecord.getMoney());
//        fundsRecord1.setTenantId(fundsRecord.getTenantId());
//        fundsRecord1.setTransDate(DateUtils.getNowDate());
//        fundsRecord1.setType(FundType.PayPaymentType.getCode());
//        fundsRecord1.setOutId(outBizNo);
//        fundsRecord1.setOrderId(fundsRecord.getOrderId());
//        fundsRecord1.setAccout(account);
//        fundsRecord1.setUserId(fundsRecord.getOurUserId());
//        fundsRecordList.add(fundsRecord1);
//        //店铺划拨数据处理
//        TransferOrderRecord transferRecord = new TransferOrderRecord();
//        transferRecord.setStatus(0);
//        transferRecord.setMoney(fundsRecord.getMoney());
//        transferRecord.setOrderId(fundsRecord.getOrderId());
//        transferRecord.setTenantId(fundsRecord.getTenantId());
//        transferRecord.setbCode(fundsRecord.getbCode());
//        transferOrderRecordService.insertTransferOrderRecord(transferRecord);
//        //本地账单存储
//        iFundsRecordService.insertFundsRecordList(fundsRecordList);
//        //最终掉支付
//        wapiFundService.fundPay(outBizNo,busiName,listFun);
//        //统一支付表插值接口
//        try{
//            ResponseEntity<ShopDetailVO> shopByShopCode = shopDetailFeignClient.getShopByShopCode(fundsRecord.getbCode());
//            if(!shopByShopCode.isSuccess()){
//                throw new Mall4cloudException(ResponseEnum.DATA_ERROR);
//            }
//
//            ResponseEntity<MchInfoVo> entity = mchInfoFeignClient.getMchInfoByMchNo(Long.valueOf(shopByShopCode.getData().getMchNo()));
//            MchInfoVo mchInfoVo = entity.getData();
//            PayOrder payOrder = new PayOrder();
//            payOrder.setPayOrderId(SeqKit.genPayOrderId());
//            payOrder.setMchNo(mchInfoVo.getMchNo());
//            //mch_name  嗨易购商城
//            payOrder.setMchName(mchInfoVo.getMchName());
//            //isv_no ==  null
//            //app_id == 传参
//            Object object = mchInfoVo.getMchAppList();
//            String appId = ((LinkedHashMap) ((ArrayList) object).get(0)).get("appId").toString();
//            payOrder.setAppId(appId);
//            //mch_type = 1(普通)
//            payOrder.setMchType(mchInfoVo.getType());
//            //mch_order_no = 订单号
//            payOrder.setMchOrderNo(String.valueOf(fundsRecord.getOrderId()));
//            //if_code     zhzjpay
//            payOrder.setIfCode("zhzjpay");
//            //way_code ZHZJ
//            payOrder.setWayCode("ZHZJ");
//            payOrder.setAmount(dec.longValue());
//            //mch_fee_rate 0
//            payOrder.setMchFeeRate(BigDecimal.valueOf(0));
//            //mch_fee_amount 0
//            payOrder.setMchFeeAmount(0L);
//            //currency cny/jsk
//            payOrder.setCurrency("cny");
//            //state 支付状态: 0-订单生成, 1-支付中, 2-支付成功, 3-支付失败, 4-已撤销, 5-已退款, 6-订单关闭
//            payOrder.setState((byte) 2);
//            //notify_state 1
//            payOrder.setNotifyState((byte) 1);
//            //client_ip ip
//            payOrder.setClientIp(IpHelper.getIpAddr());
//            //subject  商品标题
//            payOrder.setSubject(fundsRecord.getSubject());
//            //body 商品描述信息
//            payOrder.setBody(fundsRecord.getBody());
//            //refund_state 退款状态: 0-未发生实际退款, 1-部分退款, 2-全额退款
//            payOrder.setRefundState((byte) 0);
//            //refund_times  0 退款次数
//            payOrder.setRefundTimes(0);
//            //refund_amount 退款总金额,单位分
//            payOrder.setRefundAmount(0L);
//            //notify_url 非空 异步
//            payOrder.setNotifyUrl("fund_payment");
//            //created_at
//            payOrder.setCreatedAt(new Date());
//            mchInfoFeignClient.savePayOrder(payOrder);
//            weChatMsgFeignClient.orderCarry(fundsRecord.getOrderId());
//            weChatMsgFeignClient.orderPaid(fundsRecord.getOrderId());
//        }catch (Exception e){
//            log.error(e.getMessage());
//        }
//        //发送消息修改订单状态
//        List<Long> orderIds = new ArrayList<>();
//        orderIds.add(fundsRecord.getOrderId());
//        // 发送消息，订单支付成功
//        SendStatus sendStatus = orderNotifyTemplate.syncSend(RocketMqConstant.ORDER_NOTIFY_TOPIC, new GenericMessage<>(new PayNotifyBO(orderIds))).getSendStatus();
//        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
//            // 消息发不出去就抛异常，因为订单回调会有多次，几乎不可能每次都无法发送出去，发的出去无所谓因为接口是幂等的
//            throw new Mall4cloudException(ResponseEnum.EXCEPTION);
//        }
//        toSubmittedTransaction(fundsRecord.getOrderId(),fundsRecord.getUserId(),fundsRecord.getbCode());
//        return ResponseEntity.success();
//    }
//    //商品成交报送
//    private void toSubmittedTransaction(Long orderId,String userId,String bCode){
//        try{
//            ResponseEntity<OrderPriceVO> orderPrice = orderFeignClient.getOrderPrice(orderId);
//            if(!orderPrice.isSuccess()){
//                log.error("获取订单详情失败");
//                throw new Mall4cloudException("获取订单详情失败");
//            }
//            if(orderPrice.getData()==null){
//                log.error("没有该订单数据");
//                throw new Mall4cloudException("没有该订单数据");
//            }
//            ResponseEntity<ShopDetailVO> shopListByShopCode = shopDetailFeignClient.getShopByShopCode(bCode);
//            if(!shopListByShopCode.isSuccess()){
//                throw new Mall4cloudException("获取商铺账户异常");
//            }
//            if(shopListByShopCode.getData() == null && StringUtils.isEmpty(shopListByShopCode.getData().getShopAccount())){
//                throw new Mall4cloudException("获取不到发行商的账户");
//            }
//            if(shopListByShopCode.getData().getShopAccount().length()<5){
//                throw new Mall4cloudException("店铺结算账号数据格式异常");
//            }
//            TransactionAndEntrustVo transactionAndEntrustVo = new TransactionAndEntrustVo();
//            List<EntrustVo> entrustVoList = new ArrayList<>();
//            List<TransactionVo> transactionVoList = new ArrayList<>();;
//            //成交
//            TransactionVo transactionVo = new TransactionVo();
//            transactionVo.setDealId("102"+(new Date().getTime()));
//            transactionVo.setDealPrice(orderPrice.getData().getPrice());
//            transactionVo.setDealQuantity(orderPrice.getData().getAllCount());
//            transactionVo.setDealTotalPrice(0L);
////            transactionVo.setDealTotalPrice(orderPrice.getData().getTotal());
//            transactionVo.setOpenFundAccount(userId+"000");
//            transactionVo.setOpenMemCode(transactionVo.getOpenFundAccount());
////            transactionVo.setOpenMemCode(userId);
//            transactionVo.setOppFundAccount(shopListByShopCode.getData().getShopAccount().substring(0,shopListByShopCode.getData().getShopAccount().length()-3)+"000");
//            transactionVo.setOppMemCode(transactionVo.getOppFundAccount());
////            transactionVo.setOppMemCode(shopListByShopCode.getData().getShopAccount().substring(0,shopListByShopCode.getData().getShopAccount().length()-3));
//            transactionVo.setOrderId("0"+new Date().getTime());
//            transactionVo.setOppOrderId("1"+new Date().getTime());
//            transactionVo.setProductCode("MC"+orderPrice.getData().getSpuId());
//
//            //委托 发起方
//            EntrustVo entrustVo1 = new EntrustVo();
//            entrustVo1.setEntrustNo(transactionVo.getOrderId());
//            entrustVo1.setMemCode(userId);
//            entrustVo1.setOrderQuantity(orderPrice.getData().getAllCount());
//            entrustVo1.setOrderPrice(orderPrice.getData().getPrice());
//            entrustVo1.setTradeDir("1");
//            entrustVo1.setOrderTime(DateUtils.getNowDate());
//            entrustVo1.setProductCode("MC"+orderPrice.getData().getSpuId());
//            //委托 对手方
//            EntrustVo entrustVo2 = new EntrustVo();
//            entrustVo2.setEntrustNo(transactionVo.getOppOrderId());
//            entrustVo2.setMemCode(transactionVo.getOppMemCode());
//            entrustVo2.setOrderQuantity(orderPrice.getData().getAllCount());
//            entrustVo2.setOrderPrice(orderPrice.getData().getPrice());
//            entrustVo2.setTradeDir("2");
//            entrustVo2.setOrderTime(DateUtils.getNowDate());
//            entrustVo2.setProductCode("MC"+orderPrice.getData().getSpuId());
//
//            entrustVoList.add(entrustVo1);
//            entrustVoList.add(entrustVo2);
//            transactionVoList.add(transactionVo);
//            transactionAndEntrustVo.setTransactionVoList(transactionVoList);
//            transactionAndEntrustVo.setEntrustVoList(entrustVoList);
//            SendStatus stockSendStatus = orderNotifyTemplate.syncSend(RocketMqConstant.DELIVERYCARD_SUBMITTED_TOPIC, new GenericMessage<>(transactionAndEntrustVo)).getSendStatus();
//            if (!Objects.equals(stockSendStatus,SendStatus.SEND_OK)) {
//                // 消息发不出去就抛异常，发的出去无所谓
////            throw new Mall4cloudException("成交异常");
//                log.error("报送异常");
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            log.error(e.getMessage());
//        }
//
//    }
//
//    /**
//     * 提货
//     *  orderId
//     */
//    @GetMapping("/getGoods")
//    ServerResponseEntity.success() getGoods(@RequestParam Long orderId)
//    {
//        if(orderId==null){
//            return ResponseEntity.showFailMsg("订单id不能为空");
//        }
//        iFundsRecordService.getGoods(orderId);
//        return ResponseEntity.success();
//    }
//
//    /**
//     * 资金退款
//     * @param payOrderId
//     * @return
//     */
//    @Log(title = "账户资金交易", businessType = BusinessType.REFUND)
//    @Transactional
//    @PostMapping("/refunds/{payOrderId}")
//    public ApiRes refunds(@PathVariable("payOrderId") String payOrderId) {
//        RefundOrder refundOrder = new RefundOrder();
//        try {
//            String refundReason = getValStringRequired("refundReason");
//            ResponseEntity<PayOrderVo> entity = mchInfoFeignClient.getPayOrderById(payOrderId);
//            PayOrderVo payOrder = entity.getData();
//            String refunds = iFundsRecordService.refunds(Long.valueOf(payOrder.getMchOrderNo()));
//            payOrder.setRefundState(PayOrder.REFUND_STATE_ALL);
//            payOrder.setRefundAmount(payOrder.getAmount());
//            payOrder.setRefundTimes(1);
//            mchInfoFeignClient.updatePayOrderById(payOrder);
//            refundOrder.setRefundOrderId(SeqKit.genRefundOrderId()); //退款订单号
//            refundOrder.setPayOrderId(payOrder.getPayOrderId()); //支付订单号
//            refundOrder.setChannelPayOrderNo(refunds);
//            refundOrder.setMchNo(payOrder.getMchNo()); //商户号
//            refundOrder.setIsvNo(payOrder.getIsvNo()); //服务商号
//            refundOrder.setAppId(payOrder.getAppId()); //商户应用ID
//            refundOrder.setMchName(payOrder.getMchName()); //商户名称
//            refundOrder.setMchType(payOrder.getMchType()); //商户类型
//            refundOrder.setMchRefundNo(SeqKit.genMhoOrderId()); //商户退款单号
//            refundOrder.setWayCode(payOrder.getWayCode()); //支付方式代码
//            refundOrder.setIfCode(payOrder.getIfCode()); //支付接口代码
//            refundOrder.setPayAmount(payOrder.getAmount()); //支付金额,单位分
//            refundOrder.setRefundAmount(payOrder.getAmount()); //退款金额,单位分
//            refundOrder.setCurrency(payOrder.getCurrency()); //三位货币代码,人民币:cny
//            refundOrder.setState(RefundOrder.STATE_SUCCESS); //退款状态:0-订单生成,1-退款中,2-退款成功,3-退款失败
//            refundOrder.setClientIp(org.apache.commons.lang3.StringUtils.defaultIfEmpty(IpHelper.getIpAddr(), getClientIp())); //客户端IP
//            refundOrder.setRefundReason(refundReason); //退款原因
//            refundOrder.setSuccessTime(new Date()); //订单退款成功时间
//            refundOrder.setCreatedAt(new Date()); //创建时间
//            mchInfoFeignClient.saveRefundOrder(refundOrder);
//            afterSaleFeignClient.refundedUpdateStatus(Long.valueOf(payOrder.getMchOrderNo()));
//            return ApiRes.ok(refundOrder);
//        } catch (Exception e) {
//            throw new Mall4cloudException("退款失败"+e.getMessage());
//        }
//    }

}
